package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

/**
 * @author cheng
 * @since 2021/7/4
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementid, Object... params) throws Exception {

        // 将要去完成对simpleExecutor里的query方法的调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);

        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementid, Object... params) throws Exception {
        List<Object> objects = selectList(statementid, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者返回多条");
        }
    }

    // @Override
    // public Integer addOne(String statementid, Object... params) throws Exception {
    //
    //     // 对add方法进行调用
    //     SimpleExecutor simpleExecutor = new SimpleExecutor();
    //     MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
    //     Integer addNum = simpleExecutor.update(configuration, mappedStatement, params);
    //     return addNum;
    // }

    @Override
    public Integer updateOne(String statementid, Object... params) throws Exception {

        // 对update方法进行调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        Integer updateNum = simpleExecutor.update(configuration, mappedStatement, params);
        return updateNum;
    }

    // @Override
    // public Integer deleteOne(String statementid, Object... params) throws Exception {
    //
    //     // 对delete方法进行调用
    //     SimpleExecutor simpleExecutor = new SimpleExecutor();
    //     MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
    //     Integer deleteNum = simpleExecutor.update(configuration, mappedStatement, params);
    //     return deleteNum;
    // }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        // 使用JDK动态代理为Dao接口生成代理对象，并返回

        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // proxy:当前代理对象的引用；method:当前被调用方法的引用；args：传递的参数
                // 底层都是JDBC代码   根据不同情况，调用不同的方法
                // 准备参数 1.statementid：sql语句的唯一标识:namespace.id;借助method拿到当前执行的方法名和当前所在类的全限定名
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();

                String statementId = className + "." + methodName;

                // 准备参数2，params:args
                // 获取被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                String typeName = genericReturnType.getTypeName();
                // 判断是否进行了泛型类型参数化
                if (genericReturnType instanceof ParameterizedType) {
                    // 查找全部
                    List<Object> list = selectList(statementId, args);
                    return list;
                } else if (typeName.equals("java.lang.Integer")) { // 判断调用方法的类型是不是Integer，如果是则调用update方法，可以进行新增，更新和删除
                    Integer updateNum = updateOne(statementId, args);
                    return updateNum;
                } else {
                    return selectOne(statementId, args);
                }
            }
        });
        return (T) proxyInstance;
    }


}
